import {
    requestUtil,
    getbaseUrl
} from "../../utils/request"

const io  = require('../../utils/weapp.socket.io')

let news = null

Page({

    /**
     * 页面的初始数据
     */
    data: {
        swiperHeight: 0,
        title: ["进行中", "历史", "退单"],
        titleActive: 0,
        userInfo: {},
        orderList: [],
        baseUrl: "",
        limitNum:0,
        isOnReach:false,

    },

    toShopDetail(e) {
        // console.log(e.currentTarget.dataset)
        let {
            orderid,
            openid,
            orderno
        } = e.currentTarget.dataset
        wx.navigateTo({
            url: `/pages/shopDetail/shopDetail?orderId=${orderid}&openId=${openid}&orderno=${orderno}`,
        })
    },

    

    // 改变标题的索引
    changetitleActive(e) {
        let index =e.detail.index
        this.setData({
            titleActive:index,
            limitNum:0,
            isOnReach:false
        })
        this.getOrderList(index)
      
    },


    // 跳转到商店列表
    toStoreList() {
        wx.switchTab({
            url: '/pages/address/address',
        })
    },



    // 到顶触发
    onReach(){
        let isOnReach = this.data.isOnReach
        let titleActive = this.data.titleActive
       let limitNum = ++this.data.limitNum
        
       if(isOnReach){
           return
       }
       this.setData({
            limitNum
       })
       this.getScrollOrderList(titleActive)
    },

    // 获取订单数据
    getOrderList(type) {
       wx.showLoading({
         title: '数据加载中',
       })
    // console.log(type)
        let openId = this.data.userInfo.openid
        let type1 = type
        let limitNum = this.data.limitNum
        if (!openId) {
            wx.hideLoading()
            return this.setData({
                orderList: []
            })
        
        }

        let res = requestUtil({
            url: "/shop/getOrderList",
            method: "get",
            data: {
                openId,
                type1,
                limitNum
            }
        })
        res.then(({
            data
        }) => {
            // console.log(data.data)
            // console.log(data.status==200)
            if(data.status==200){
                // console.log(data.data)
                let newArr2 = data.data.filter(item => {
                    item.totalPrice = parseFloat(item.orderList.reduce((total, current) => {
                        return total += current.num * current.price
                    }, 0))
                    item.num = item.orderList.length
                    if (item.shopDiscount.length > 0) {
                        item.rmb = item.shopDiscount[0].disRmb
    
                    } else {
                        item.rmb = 0
                    }
                    item.totalPrice = (item.totalPrice - item.rmb).toFixed(2)
                    return item
                })
    
    
                this.setData({
                    orderList:newArr2
                })
                wx.hideLoading()
            }else{
                
                // console.log(data.data)
                    this.setData({
                        isOnReach:true,
                        limitNum:0,
                        orderList:data.data
                    })
                
                wx.hideLoading()
            }
        },e=>{
            wx.hideLoading()
        })

    },

        // 滚动获取订单数据
        getScrollOrderList(type) {
            //    wx.showLoading({
            //      title: '数据加载中',
            //    })
            // console.log(type)
                let openId = this.data.userInfo.openid
                let type1 = type
                let limitNum = this.data.limitNum
                if (!openId) {
                    return this.setData({
                        orderList: []
                    })
                }
        
                let res = requestUtil({
                    url: "/shop/getOrderList",
                    method: "get",
                    data: {
                        openId,
                        type1,
                        limitNum
                    }
                })
                res.then(({
                    data
                }) => {
                    // console.log(data.status==200)
                    if(data.status==200){
                        // console.log(data.data)
                        let newArr2 = data.data.filter(item => {
                            item.totalPrice = parseFloat(item.orderList.reduce((total, current) => {
                                return total += current.num * current.price
                            }, 0))
                            item.num = item.orderList.length
                            if (item.shopDiscount.length > 0) {
                                item.rmb = item.shopDiscount[0].disRmb
            
                            } else {
                                item.rmb = 0
                            }
                            item.totalPrice = (item.totalPrice - item.rmb).toFixed(2)
                            return item
                        })
            
            
                        this.setData({
                            orderList: [...this.data.orderList, ...newArr2]
                        })
                        wx.hideLoading()
                    }else{
                        
                        // console.log(data.data)
                            this.setData({
                                isOnReach:true,
                                limitNum:0
                                
                            })
                        
                        // wx.hideLoading()
                    }
                },e=>{
                    // wx.hideLoading()
                })
        
            },


    // 深拷贝
    deepCopy(data) {


        let res = data instanceof Array ? [] : {}
        for (const [k, v] of Object.entries(data)) {
            res[k] = typeof v === "object" ? this.deepCopy(v) : v
        }
        return res

        // console.log(data instanceof Array)
    },

    received(){
        let openId = this.data.userInfo.openid?this.data.userInfo.openid:''
        let baseUrl = getbaseUrl()
         news = io(baseUrl)
        news.on('connect',(res)=>{
            console.log('connection created.')
        })
        news.on(`${openId}`,(data)=>{
            console.log("监听到了")
            // console.log(this.data.limitNum)
            this.setData({
                limitNum:0,
                isOnReach:false
            })

    
            this.getOrderList(this.data.titleActive)

        })
      
          

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // that = this
        // this.received()
        setTimeout(()=>{
            this.received()
        },50)
    //   this.setData({
    //     titleActive:0
    //   })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        // 获取屏幕可用区
        let res = wx.getSystemInfoSync()

        this.setData({
            swiperHeight: res.windowHeight - 50
        })

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // wx.showLoading({
        //     title: '数据加载中',
        // })
        this.setData({
            baseUrl: getbaseUrl() + "/image/",
            orderList: [],
            limitNum:0,
        })


        wx.getStorage({
            key: "userInfo",
            success: ({
                data
            }) => {
                this.setData({
                    userInfo: JSON.parse(data),
                })
                this.getOrderList(this.data.titleActive)
                
            },
            fail: () => {
               
            }
        })


    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        news.disconnect()
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})